<template>
  <div>
    <el-popover placement="bottom" :width="300" :visible="visible">
      <template #reference>
        <el-button
          :class="[freshType == 'error' ? 'vibrate-fast' : '']"
          link
          :type="freshType"
          size="small"
          @click="handleOpen()"
        >
          <el-icon v-if="freshType == 'primary'"><SuccessFilled /></el-icon>
          <el-icon v-else-if="freshType == 'info'"><InfoFilled /></el-icon>
          <el-icon v-else><WarningFilled /></el-icon>
          <span>数据</span>
          <span v-if="loaderMode == 'history'">&nbsp;(当前为历史数据)</span>
        </el-button>
      </template>
      <div class="pop-header">
        <el-button :type="freshType" size="small" link>
          <span v-if="loaderMode == 'real'" class="vertical-align-center">
            <el-icon v-if="freshType == 'primary'"><SuccessFilled /></el-icon>
            <el-icon v-else><WarningFilled /></el-icon>
            <span>数据更新于</span>
            <b>{{ freshTime }}</b>
            <span>分钟前</span>
          </span>
          <span v-else class="vertical-align-center">
            <el-icon><InfoFilled /></el-icon>
            <span>当前为历史数据</span>
          </span>
        </el-button>
        <el-button type="info" link size="small" @click="handleClose()">
          <el-icon><Close /></el-icon>
        </el-button>

        <!-- <el-divider /> -->
      </div>
      <div class="pop-body">
        <el-form label-width="42px" size="small">
          <el-form-item> </el-form-item>
          <el-form-item label="起始">
            <el-date-picker
              v-model="flowStore.loaderConfigAirports.history.date1"
              type="date"
              placeholder=""
              format="YYYY-MM-DD"
              style="width: 110px"
              :clearable="false"
              :disabled-disposed="loaderMode != 'history'"
            />
            <span style="padding: 0 2px"></span>
            <el-input-number
              v-model="flowStore.loaderConfigAirports.history.hour1"
              :min="0"
              :max="23"
              controls-position="right"
              style="width: 70px"
            />
            <span style="padding: 0 2px"></span>
            <el-text type="info">时</el-text>
          </el-form-item>
          <el-form-item label="结束">
            <el-date-picker
              v-model="flowStore.loaderConfigAirports.history.date2"
              type="date"
              placeholder=""
              format="YYYY-MM-DD"
              style="width: 110px"
              :clearable="false"
              :disabled-disposed="loaderMode != 'history'"
            />
            <span style="padding: 0 2px"></span>
            <el-input-number
              v-model="flowStore.loaderConfigAirports.history.hour1"
              :min="0"
              :max="23"
              controls-position="right"
              style="width: 70px"
            />
            <span style="padding: 0 2px"></span>
            <el-text type="info">时</el-text>
          </el-form-item>
          <div style="text-align: center">
            <el-button
              type="primary"
              :link="loaderMode != 'history'"
              @click="handleLoad('history')"
              >载入历史数据</el-button
            >
            <el-button
              type="primary"
              :link="loaderMode != 'real'"
              @click="handleLoad('real')"
              >载入实时数据</el-button
            >
          </div>
        </el-form>
      </div>
    </el-popover>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";

import useFlowStore from "@/store/flow.js";
const flowStore = useFlowStore();

const emits = defineEmits(["change"]);

const isLoading = ref(false);

const visible = ref(false);
const handleOpen = () => {
  visible.value = !visible.value;
  // visible.value = true;
};
const handleClose = () => {
  visible.value = !visible.value;
  // visible.value = false;
};

const loaderMode = computed(() => flowStore.loaderConfigAirports.mode);

const freshness = computed(() => flowStore.freshnessAirports);
const freshTime = computed(() => Math.round(flowStore.freshnessAirports / 60));
const freshType = computed(() =>
  loaderMode.value == "history"
    ? "info"
    : flowStore.freshnessAirports < 900
    ? "primary"
    : "error"
);

// const hourList = ref([...new Array(24).keys()]);

// const loaderMode = ref("real");

const handleLoad = (loaderMode = "real") => {
  if (loaderMode == "real") {
    flowStore.loaderConfigAirports.mode = "real";
    flowStore.loaderConfigAirports.autoRefresh = true;
    flowStore.loaderConfigAirports.fakeDate = false;
    flowStore.loaderConfigAirports.customDate = "";
    flowStore.loaderConfigAirports.ignoreWarning = false;
    flowStore.getAirportFlowData().then(() => {
      visible.value = false;
      emits("change");
    });
  } else if (loaderMode == "history") {
    flowStore.loaderConfigAirports.mode = "history";
    flowStore.loaderConfigAirports.autoRefresh = false;
    flowStore.loaderConfigAirports.ignoreWarning = true;
    let params = getLoaderParams({
      date1: flowStore.loaderConfigAirports.history.date1,
      hour1: flowStore.loaderConfigAirports.history.hour1,
      date2: flowStore.loaderConfigAirports.history.date2,
      hour2: flowStore.loaderConfigAirports.history.hour2,
    });
    loadData({
      start: params.start,
      end: params.end,
    }).then((res) => {
      visible.value = false;
      console.log("历史数据", res);
      emits("change");
    });
  }
};

const getLoaderParams = ({ date1, hour1, date2, hour2 }) => {
  let nowDay = dayjs();
  let startDay = dayjs(date1) //flowStore.loaderConfigAirports.history.date1
    .hour(hour1) //flowStore.loaderConfigAirports.history.hour1
    .minute(0)
    .second(0);
  let endDay = dayjs(date2) //flowStore.loaderConfigAirports.history.date2
    .hour(hour2) //flowStore.loaderConfigAirports.history.hour2
    .minute(0)
    .second(0);
  let before = startDay.isBefore(endDay);
  let length = endDay.diff(startDay, "hour");
  let passed = true;
  // nowDay.isAfter(startDay, "hour") && nowDay.isAfter(endDay, "hour");
  let valid = before && length >= 0 && passed;
  let params = {
    start: startDay.format("YYYY-MM-DD HH:mm:ss"),
    end: endDay.format("YYYY-MM-DD HH:mm:ss"),
    before,
    length,
    valid,
  };
  return params;
};

const loadData = ({ start, end }, writeStore = true) => {
  flowStore.replyDataAirports = null;
  let uri = `api/flow_ntfm_get_airports.php?&tag=1&begTime=${start}&endTime=${end}&tnr=1`;
  return new Promise((resolve, reject) => {
    axios
      .get(uri)
      .then((response) => {
        if (writeStore) {
          flowStore.rawDataAirports = response.data.content;
          flowStore.rawRateAirports = response.data.rates;
          flowStore.begTimeAirports = response.data.begTime;
          flowStore.tagsAirportFlow = response.data.tags;
          flowStore.airportFlowLimits = response.data.limits;
          flowStore.versionAirports = -1;
          flowStore.freshnessAirports = 0;
        }

        flowStore.replyDataAirports = response.data;
        resolve(response.data);
      })
      .catch((error) => {
        console.error("flow_ntfm_get_airports", error);
        reject(error);
      });
  });
};
</script>

<style scoped>
@import "@/styles/vibrate.css";
@import "@/styles/blinking.css";

.pop-header {
  padding: 12px 8px 16px 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pop-body {
  border-top: 1px solid #8884;
  padding: 0 8px 16px 8px;
  width: 100%;
  min-width: 100%;
  max-width: 100%;
}
</style>
